<?php


namespace App\Http\Controllers\Weapp;


use App\Service\Weapp\WeappInterface;
use App\Service\WeappToken\WeappTokenInterface;
use App\Tool\Json;



class Login extends Base
{




    function getSessionKey(WeappInterface $weapp){

        $code=request()->input('code');


        $data=$weapp->requestSessionKey($code);


        return Json::code(1,'success',$data);


    }

    /**
     *
     * Create by Peter
     * 2019/12/05 13:09:52
     * Email:904801074@qq.com
     * @param WeappInterface $weapp
     * @param WeappTokenInterface $weappToken
     * @return false|string
     */
    function getPhone(WeappInterface $weapp,WeappTokenInterface $weappToken){

        try {

            $encryptedData = request()->input('encryptedData', '');

            $iv = request()->input('iv', '');

            $sessionKey = request()->input('sessionKey', '');


            $data = $weapp->decrypt($encryptedData, $iv, $sessionKey);

            $data = json_decode($data, true);

            $phone = $data['phoneNumber'];

            if (!$phone) return Json::code(2, '手机号不能为空');


            $user = \App\Model\User::updateOrCreate(['phone' => $phone], ['phone' => $phone]);

            $token = $weappToken->saveToken($user->id, 1, 60 * 60 * 24 * 3);

            return Json::code(1, $data, $token);

        }catch (\Exception $exception){

            return Json::code(31,$exception->getMessage());

        }

    }


    function getInfo(){

        $token=request()->header('token');

        if(!$token) return Json::code(2,'token不存在！');

        $info=$this->getUserInfo($token);

        if(!$info) return Json::code(2,'token未找到！');

        return Json::code(1,'success',$info);



    }



}
